package com.dbMethod;

import com.lUtils.jdbcUtils;

import java.sql.*;
import java.time.LocalDateTime;

public class sql_UpdateWithdraw {
    public static void UpdateWithdraw(String CardId, String tradeType, LocalDateTime transDate, int Money){
        Connection con = null;
        PreparedStatement psTrans = null;
        PreparedStatement psUpdateBalance = null;
        ResultSet rs = null;

        try{
            con= jdbcUtils.getConnection();
            // 关闭自动提交，开启事务
            con.setAutoCommit(false);

            // 1. 插入交易记录到 transinfo 表
            psTrans = con.prepareStatement("insert into  transinfo (`cardID`,`transType`,`transDate`,`transMoney`)  values (?,?,?,?) ");
            psTrans.setString(1,CardId);
            psTrans.setString(2,tradeType);
            psTrans.setTimestamp(3, Timestamp.valueOf(transDate));
            psTrans.setInt(4, Money);
            psTrans.executeUpdate();

            // 2. 更新 cardinfo 表中的 balance
            String updateBalance = "update cardinfo set balance = balance - ? where cardID = ?";
            psUpdateBalance = con.prepareStatement(updateBalance);
            psUpdateBalance.setInt(1, Money);
            psUpdateBalance.setString(2, CardId);
            psUpdateBalance.executeUpdate();

            // 提交事务
            con.commit();
            System.out.println("交易成功，余额已更新。");


        }catch (SQLException e){
            // 如果出现异常，回滚事务
            try {
                if (con != null) {
                    con.rollback();
                }
            } catch (SQLException rollbackEx) {
                rollbackEx.printStackTrace();
            }
            e.printStackTrace();
        }
        finally {
            jdbcUtils.closeTheStream(rs, psTrans, con);
            jdbcUtils.closeTheStream(null, psUpdateBalance, null);
        }
    }
}
